/*
** SMSE2K for Windows console
** TODO: Direct sound output instead of through output PCM crap
*/

#include <stdio.h>
#include <windows.h>
#include <conio.h>
#include <dsound.h>
#include "smse2k.h"

int done = 0;

// ********** DebugTrap
// This is a CPU debugger trap, called in every CPU. This sucks in terms of debugger stuff.
void DebugTrap(UINT64 pc) {
	printf("*** CPU Step 0x%08X, press a key to step into code\n",pc);
	getchar();
}

// seems to get stuff playing correctly
#define BUFFER_SIZE 200000

int main (int argc, char** argv) {
	HSmseContext* ctx = SMSE_NewContext();
	short* fakebuffer = malloc(BUFFER_SIZE * 2);
	FILE* f = fopen("out.pcm","wb");
	int i =0, track = 0;
	const char* fn = NULL;
	const char* drv = NULL;
	int isStartingDriver = 0;
	UINT32 code = 0x00; // default sound code to launch
	int errcode;

	if (argc < 2) {
		printf("SUPER MEGA SOUND EMULATOR 2000 (c) unknownfile R&D\n");
		printf("Usage: smse2k [arguments] soundfile\n");

		return 1;
	}


	// Loop through arguments
	for (i=1; i < argc; i++) {

		// if we're on the last argument, let's use that as a filename
		if (i == (argc-1)) {
			fn = argv[i];
			break;
		}


		// -stats: Output core stats and exit
		if (!strcmp("-stats",argv[i])) {
			SMSE_Stats();
			return 0;
		}

		// -d=driver: starts up a driver. all arguments past this are ignored
		if (!memcmp("-d=",argv[i],3)) {
			drv = argv[i] + 3;
			//printf("Starting up driver %s\n",argv[i] + 3);
			//if (SMSE_BootDriver(ctx, argv[i] + 3)) {
			//	printf("Can't boot driver, see error log for more information\n");
			//	return 1;
			//}

			break;
		}

		// -c=soundcode: Starts up the track with a sound code
		if (!memcmp("-c=",argv[i],3)) {
			sscanf(argv[1]+3,"%x",&code);
		}

		

	}

	


	SMSE_SetOutput(ctx,44100,2);

	if (isStartingDriver) {
		if (SMSE_BootDriver(ctx, drv)) {
			printf("Can't boot driver, see error log for more information\n");
				return 1;
		}
	} else {	
		printf("Opening file %s\n",fn);
		if (SMSE_LoadFile(ctx, fn)) {
			printf("Load failed\n");
			return 1;
		}
	}

	printf("Load successful!\n");

	printf("Now running. Press any key to exit\n");

	SMSE_SetTrack(ctx, code);  // Parodius Air Battle

	// This main loop needs to be changed to directly output audio
	while (1) {
		int buffered_stuff = SMSE_Buffer(ctx,fakebuffer,BUFFER_SIZE);
		fwrite(fakebuffer,buffered_stuff * sizeof(short),1,f);
		
		//if (kbhit()) break;
		Sleep(1);
	}

	// Close the context

	printf("Have a nice day\n");

	return 0;
}